const fs = require('fs');
const path = require('path');
const getInfo = require('image-size')
var child_process = require('child_process');
const { dir } = require('console');

var current = process.cwd(); // 当前路径

var isWindows = path.sep === '\\'

const resPath = current.split('image-tool')[0] + 'sesame-unity/sesame/Assets/Game/Res';
const dynamicPath = path.join(resPath, 'Dynamic');
const cdnPath = path.join(resPath, 'CDN');

// 创建透明图片：magick -resize 256x256 1.png 256.png
function createImg(sizeX, sizeY) {
  child_process.execSync(`magick 1.png -resize ${sizeX}x${sizeY}! ${sizeX}x${sizeY}.png`);
}

/**
 * -resize 宽x高 
 * -resize 200x100! 不管原图片比例如何，缩放后的图片大小都是200×100
 * -resize 200 得到图片宽为200，高根据原始图片比例计算而来
 * -resize x100 得到的图片高位100，宽根据原始图片比例计算而来
 */
function resizeBatch(dir, sizeX, sizeY) {
  if (isWindows) {
    fs.readdirSync(dir).forEach((x) => {
      if (x.indexOf('.') === -1 || x.endsWith('meta')) return;
      child_process.execSync(`magick ${path.join(dir, x)} -resize ${sizeX}x${sizeY}! ${path.join(dir, x)}`)
    })
    return
  }
  const newDir = dir + '_NEWRES';
  console.log('newDir:', newDir);
  if (!fs.existsSync(newDir)) {
    fs.mkdirSync(newDir, { recursive: true });
  }
  if (sizeX && sizeY) {
    child_process.execSync(`mogrify -path ${newDir}/ -resize ${sizeX + 'x' + (sizeY ?? sizeX)}! ${dir}/*.png`)
  } else if(sizeX) {
    child_process.execSync(`mogrify -path ${newDir}/ -resize ${sizeX} ${dir}/*.png`)
  } else if(sizeY) {
    child_process.execSync(`mogrify -path ${newDir}/ -resize x${sizeY} ${dir}/*.png`)
  }

  console.log(`将${dir}下的全部文件都调整成${sizeX + 'x' + (sizeY ?? sizeX)}大小 ==> 完成`);
}

function expendBatch(dir, sizeX, sizeY) {
  const newDir = dir + '_NEWRES';
  if (!fs.existsSync(newDir)) {
    fs.mkdirSync(newDir, { recursive: true });
  }
  if (!fs.existsSync(path.join(current, `${sizeX}x${sizeY}.png`))) {
    createImg(sizeX, sizeY);
  }
  fs.readdirSync(dir).forEach((fileName) => {
    if (!fileName.endsWith('.png')) return;
    if (isWindows) {
      child_process.execSync(`magick ${sizeX}x${sizeY}.png -gravity center -compose over ${path.join(dir, fileName)} -colorspace sRGB -composite ${path.join(newDir, fileName)}`)
    } else {
      child_process.execSync(`convert ${sizeX}x${sizeY}.png -gravity center -compose over ${path.join(dir, fileName)} -colorspace sRGB -composite ${path.join(newDir, fileName)}`)
    }
  });
}

function cropBatch(dir, crop) {
  if (isWindows) {
    fs.readdirSync(dir).forEach((x) => {
      if (x.indexOf('.') === -1 || x.endsWith('meta')) {
        return;
      }
      child_process.execSync(`magick ${path.join(dir, x)} -crop ${crop} ${path.join(dir, x)}`)
    })
    return;
  }
  const newDir = dir + '_NEWRES';
  if (!fs.existsSync(newDir)) {
    fs.mkdirSync(newDir, { recursive: true });
  }
  child_process.execSync(`mogrify -path ${newDir} -crop ${crop} ${path.join(dir, '*.png')}`)
}

function cropSingle(paraentDir, fileName, crop) {
  child_process.execSync(`magick -crop ${crop} ${path.join(paraentDir, fileName)} ${path.join(paraentDir, 'New_' + fileName)}`)
}

function dealCDNSkin() {
  const skinPath = path.join(cdnPath, 'Partial', 'SKin');
  for (let i = 1; i <= 240; i++) {
    console.log('正在执行中...' + i);
    const dirPath = path.join(skinPath, i.toString());
    if (!fs.existsSync(dirPath)) continue;
    const nocloth = path.join(dirPath, `nocloth_${i}.png`);
    const isWife = fs.existsSync(nocloth);
    const fullPath = path.join(dirPath, `full_${i}.png`);
    const headPath = path.join(dirPath, `head_${i}.png`);
    const iconPath = path.join(dirPath, `icon_${i}.png`);
    // icon resize to 128*128， 直接覆盖 (已执行)
    // child_process.execSync(`magick ${iconPath} -resize 128x128! ${iconPath}`);
    if (isWife) {
      // 红颜全身 和 半裸 扩展像素点到1024*1024 （已执行）
      // if (fs.existsSync(fullPath)) {
      //   child_process.execSync(`magick 1024x1024.png -gravity center -compose over ${fullPath} -composite ${fullPath}`)
      // } else {
      //   console.log(`红颜 ${i} 没有全身图`)
      // }
      // child_process.execSync(`magick 1024x1024.png -gravity center -compose over ${nocloth} -composite ${nocloth}`)

      // 头像裁剪
      if (fs.existsSync(headPath)) {
        child_process.execSync(`magick ${headPath} -crop 256x256+74+0 ${headPath}`)
      } else {
        console.log(`红颜 ${i} 没有头像`)
      }
    } else {
      // 1、门客头像删除 （已执行）
      // if (fs.existsSync(headPath)) {
      //   fs.rmSync(headPath)
      // }
      // 2、门客全身像扩展像素到512*512（已执行）
      // if (fs.existsSync(fullPath)) {
      //   child_process.execSync(`magick 512x512.png -gravity center -compose over ${fullPath} -composite ${fullPath}`)
      // } else {
      //   console.log(`门客 ${i} 没有全身图`)
      // }
    }
  }
}


function GetPathes(parentPath, filePathes, format) {
  format = format ?? '.png'// 默认处理透明图片
  const pathes = fs.readdirSync(parentPath);
  pathes.forEach((fileName) => {
    let isFile = fileName.indexOf('.') >= 0;
    const fullPath = path.join(parentPath, fileName)
    if (fileName.indexOf('VERSION') >= 0) return;
    if (fileName.indexOf('sheet') >= 0) return;
    if (!isFile && fileName.toLowerCase().indexOf('placeholder') >= 0) return;
    if (fullPath.indexOf('num' + path.sep) >= 0) return;
    if (isFile) {
      if (fileName.toLowerCase().endsWith(format)) { 
        filePathes.push(fullPath);
      }
    } else {
      GetPathes(path.join(fullPath), filePathes, format);
    }
  });
}

function getPowerOf2(x) {
  let power = 0;
  while(2 ** power < x) {
    power += 1;
  }
  return 2 ** power;
}

function expendAll() {
  const dir = path.join(resPath, 'LuaAssets', 'image');
  // const newDir = path.replace('Res', 'Res_New')
  const filePathes = [];
  GetPathes(dir, filePathes);
  const fileCount = filePathes.length;
  const errorFiles = [];
  for (let index = 0; index < fileCount; index++) {
    const filePath = filePathes[index];
    const size = getInfo(filePath)
    const newWidth = getPowerOf2(size.width);
    const newHeight = getPowerOf2(size.height);
    if (newWidth === size.width && newHeight === size.height) {
      // console.log(`进度：${index + 1}/${fileCount}  已经是2次幂了  路径： ${filePath}`);
      continue;
    }
    const subDirPath = filePath.replace(resPath, '');
    if (subDirPath.indexOf('(') >= 0 || subDirPath.indexOf(')') >= 0 || subDirPath.indexOf(' ') >= 0) {
      console.log(`进度：${index + 1}/${fileCount}  文件名称有问题  路径： ${filePath}`);
      errorFiles.push(filePath);
      continue;
    }
    
    const newFilePath = filePath.replace(path.join('Assets', 'Game'), path.join('New_Assets', 'Game'));
    if (fs.existsSync(newFilePath)) {
      // console.log(`进度：${index + 1}/${fileCount}  已经生成过了  路径： ${newFilePath}`);
      continue;
    }
    const newFileDirPath = newFilePath.substring(0, newFilePath.lastIndexOf(path.sep))
    console.log(`进度：${index + 1}/${fileCount}  ${size.width}x${size.height} => ${newWidth}x${newHeight}  路径： ${filePath}`);
    if (!fs.existsSync(newFileDirPath)) {
      fs.mkdirSync(newFileDirPath, { recursive : true });
    }
    if (!fs.existsSync(path.join(current, `${newWidth}x${newHeight}.png`))) {
      createImg(newWidth, newHeight);
    }
    child_process.execSync(`magick ${newWidth}x${newHeight}.png -gravity center -compose over -colorspace sRGB ${filePath} -composite ${newFilePath}`)
  }
  console.log('完成');
  errorFiles.forEach((x) => console.log('有问题的文件:' + x));
}

// expendAll();


// dealCDNSkin();

// child_process.execSync(`mogrify -path ${genDirPath} -resize ${resize} -crop ${crop} ${fullDirPath}/*.png`)

// createImg(256, 512)
// resizeBatch(path.join(dynamicPath, 'Child', 'AdultGirl'), 512)
// expendBatch(path.join(dynamicPath, 'Child', 'GirlHead'), 256, 256)
// expendBatch(path.join(dynamicPath, 'Child', 'MinorGirl'), 512, 512)

// resizeBatch(path.join(dynamicPath, 'Child', 'Prince'), null, 512)

// resizeBatch(path.join(dynamicPath, 'YaMen', 'Skill'), 128, 128)

// resizeBatch(path.join(dynamicPath, 'Rank'), 64, 64)
// cropSingle(path.join(dynamicPath, 'Boss'), 'RaidRaidEnemy0.png', '495x512+0+10')

// 门客头像
// cropBatch(path.join(dynamicPath, 'Servant', 'Half'), '229x256+0+5')
// expendBatch(path.join(dynamicPath, 'Servant', 'Half'), 256, 256)

// 皮肤背景
// expendBatch(path.join(dynamicPath, 'Skin', 'Background'), 1024, 1024)

// 红颜头像, 偏移值不是（420-256）/2的原因是 转过后，放在头像里，还需要x轴偏移，所以这边就直接把偏移做好了
// cropBatch(path.join(dynamicPath, 'Wife', 'Head'), '256x256+74+0')

// 玩家身体
// cropBatch(path.join(cdnPath, 'fashion'), '750x1024+0+210')
// expendBatch(path.join(cdnPath, 'fashion_NEWRES'), 1024, 1024)

// 玩家头像 （pivot: (0.5, 1)  布局居顶部
// cropBatch(path.join(dynamicPath, 'PlayerHead'), '512x512+119+200')
// CDN 玩家头像
// cropBatch(path.join(cdnPath, 'Partial', 'Head2'), '512x512+119+200')
// 单独处理头像 PakUserFigureHead6（辫子超出了一点点）
// const headPath = path.join(cdnPath, 'Partial', 'Head2', '10888.png');
// child_process.execSync(`convert ${headPath} -crop 512x1024+119+200 ${headPath}`)

// 城郊背景
// const bgPath = path.join(resPath, 'LuaAssets', 'image', 'city', 'bg', 'city_bg_bg1.png')
// child_process.execSync(`magick 4096x1024.png -gravity north -compose over -colorspace sRGB ${bgPath} -composite ${bgPath}`)
// const bgPath = path.join(resPath, 'LuaAssets', 'image', 'city', 'bg', 'city_bg_bg3.png')
// child_process.execSync(`magick 4096x512.png -gravity center -compose over -colorspace sRGB ${bgPath} -composite ${bgPath}`)


// 府邸背景 Game\Res\LuaAssets\image\homeBg
// D:\Workspace\sesame-unity\sesame\Assets\Game\Res\LuaAssets\image\scene2\allianceTribute\build
function resizeImg(fullPath, sizeStr, oldSizeStr) {
  fullPath = fullPath.replace('/', path.sep).replace('\\', path.sep);
  const info = getInfo(fullPath);
  const oldSize = oldSizeStr ?? `${info.width}x${info.height}`
  const newPath = fullPath.replace('.', `_${oldSize}.`);
  fs.renameSync(fullPath, newPath)
  fs.renameSync(fullPath + '.meta', fullPath.replace('.', `_${oldSize}.`) + '.meta')
  child_process.exec(`magick ${newPath} -resize ${sizeStr}! ${newPath}`)
}
// resizeImg(path.join(resPath, 'LuaAssets\\image\\scene\\alliance\\bg\\alliance_bg_bg14.png'), '512x1024')
// resizeImg(path.join(resPath, 'LuaAssets', 'image', 'scene2\\raiseArmy\\fightView\\fightBg', 'fightView_fightBg_7.png'), '512x1024')
// const bgPath = path.join(resPath, 'LuaAssets\\image\\bg\\image_bg_bg359.png');
// child_process.execSync(`magick ${bgPath} -crop 734x1024+0+137 ${bgPath}`)

// cropBatch(path.join(resPath, 'LuaAssets', 'image', 'scene2/raiseArmy/fightView/fightBg'), '700x1024+0+2')
// expendBatch(path.join(resPath, 'CDN', 'SkinTheme'), 1024, 256)

// resizeImg(path.join(resPath, 'LuaAssets\\image\\scene\\alliance\\bg\\alliance_bg_bg14.png'), '512x1024')
// resizeImg(path.join(resPath, 'LuaAssets', 'image', 'scene\\ring\\bg', 'ring_bg_bg6.png'), '512x1024')
// resizeImg(path.join(resPath, 'LuaAssets', 'image', 'scene2\\raiseArmy\\recruitArmy\\shoper', 'recruitArmy_shoper_243.png'), '512x1024')

function dealOther() {
  function getLessPower(x) {
    let power = 0;
    while(2 ** power <= x) {
      power += 1;
    }
    return 2 ** (power - 1);
  }

  const dir = path.join(resPath)
  // const newDir = path.replace('Res', 'Res_New')
  const filePathes = [];
  GetPathes(dir, filePathes, '.jpg');
  for (let i = 0; i < filePathes.length; i++) {
    const fullPath = filePathes[i];
    const info = getInfo(fullPath)
    // if (info.width <= 1024 && info.height <= 1024) {
    //   // console.log('可以做扩展')
    //   continue;
    // }
    if (getLessPower(info.width) === info.width && getLessPower(info.height) === info.height) {
      // console.log('尺寸相同')
      continue;
    }
    // console.log(info.width, info.height, fullPath)
    const res = fs.readFileSync(fullPath + '.meta').toString();
    if (res.indexOf('nPOTScale: 1') === -1) {
      console.log('need to near', fullPath);
      let content = res.replace('nPOTScale: 0', 'nPOTScale: 1');
      content = content.replace('nPOTScale: 2', 'nPOTScale: 1');
      content = content.replace('nPOTScale: 3', 'nPOTScale: 1');
      fs.writeFileSync(fullPath + '.meta', content);
    }
    // if ((info.width <= 1024 && info.width > 512) && (info.height > 1024)) {
    //   // resizeImg(fullPath, '512x1024');
    //   continue;
    // }
  }
}

// dealOther();
// const res = child_process.execSync(`magick identify ${path.join(cdnPath, 'SkinTheme', 'small_0.png')}`)
// const res2 = child_process.execSync(`magick identify ${path.join(cdnPath, 'SkinTheme', 'big_0.jpg')}`)
// console.log('res:', res.toString());
// console.log('res:', res2.toString());

// resizeImg(fullPath, '512x1024');

function toNearest(dir) {
  function getNearSize(x) {
      let power = 0;
      while(2 ** power <= x) power += 1;
      power -= 1;
      const minV = 2 ** power;
      const maxV = 2 ** (power + 1)
      return (maxV - x > x -minV) ? minV : maxV;
  }
  const filePathes = [];
  GetPathes(dir, filePathes, '.jpg');
  // GetPathes(dir, filePathes, '.jpg');
  const count = filePathes.length;
  let index = 0;
  for (let i = 0; i < count; i++) {
    const info = getInfo(filePathes[i]);
    const newWidth = getNearSize(info.width);  
    const newHeight = getNearSize(info.height);
    if (newWidth === info.width && newHeight == info.height) {
      continue;
    }

    if (info.width > 1024 || info.height > 1024) {
      const metaPath = filePathes[i] + '.meta';
      const res = fs.readFileSync(metaPath).toString();
      if (res.indexOf('nPOTScale: 0') >= 0) {
        console.log(`${index} / ${count} --- ${JSON.stringify(info)} 路径：${filePathes[i]}`)
      }
      continue;
    }
    if (info.width <= 1024 && info.height <= 1024) {
      const x = getPowerOf2(info.width);
      const y = getPowerOf2(info.height);

      index++;
      console.log(`${index} / ${count} --- ${JSON.stringify(info)} 路径：${filePathes[i]}`)
      // child_process.execSync(`magick ${x}x${y}.png -gravity center -compose over ${filePathes[i]} -colorspace sRGB -composite ${filePathes[i]}`)

      // child_process.execSync(`magick ${filePathes[i]} -resize ${newWidth}x${newHeight}! ${filePathes[i]}`)
      // fs.renameSync(`${filePathes[i]}`, `${filePathes[i].replace('.', `_${info.width}x${info.height}.`)}`)
      // fs.renameSync(`${filePathes[i]}.meta`, `${filePathes[i].replace('.', `_${info.width}x${info.height}.`)}.meta`)
      // const metaPath = filePathes[i] + '.meta';
      // const res = fs.readFileSync(metaPath).toString();
      // if (res.indexOf('nPOTScale: 1') >= 0) {
      //   console.log(`${index} / ${count} --- ${JSON.stringify(info)} 路径：${filePathes[i]}`)
      // //   const content = res.replace('nPOTScale: 0', 'nPOTScale: 1');
      // //   fs.writeFileSync(metaPath, content);
      // }
    }
    
    // child_process.execSync(`convert ${sizeX}x${sizeY}.png -gravity center -compose over ${path.join(dir, fileName)} -colorspace sRGB -composite ${path.join(newDir, fileName)}`)
    
    
    // if (res.indexOf('nPOTScale: 0')) {
      // index += 1;
      // console.log(`${index} / ${count} --- ${JSON.stringify(info)} 路径：${filePathes[i]}`)
    // }

  }
}
// toNearest(path.join(resPath, 'LuaAssets', 'image'));
// const basePath = path.join(resPath, 'LuaAssets', 'image', 'story', 'scene')
// child_process.execSync(`magick ${path.join(basePath, 'story_scene_1.jpg')} -resize 750x1334! ${path.join(basePath, 'story_scene_1.jpg')}`)
// const basePath = path.join(resPath, 'LuaAssets', 'image', 'map', 'npcbody_new')
// cropBatch(basePath, '700x1024+0+2')
// expendBatch(basePath + '_NEWRES', 1024, 1024)
// const basePath = path.join(dynamicPath, 'Affairs');
// fs.readdirSync(basePath).forEach((x) => {
//   fs.renameSync(path.join(basePath, x), path.join(basePath, x.replace('bg_affairs_', 'Bg')));
// })
// expendBatch(path.join(dynamicPath, 'Map', 'NpcBody'), 512, 512)
// cropBatch(path.join(dynamicPath, 'Map', 'NpcBodyChapter'), '700x1024+0+2')
// expendBatch(path.join(dynamicPath, 'HeadBg'), 512, 512)
// resizeBatch(path.join(dynamicPath, 'HeadBg'), 128, 128)

// const basePath = path.join('D:', 'Spine', 'Anim');
// const skinPath = path.join(cdnPath, 'Partial', 'Skin');
// const arr = [];
// fs.readdirSync(skinPath).forEach((x) => {
//   if (!fs.existsSync(path.join(skinPath, x, 'Spine'))) return;
//   if (fs.existsSync(basePath, x)) {
//     arr.push(x);
//   }
// })
// console.log('存在资源', arr.length, ' -- ', arr);
// fs.readdirSync(skinPath).forEach((x) => {
//   if (fs.existsSync(path.join(skinPath, x, 'Spine'))) {
//     fs.rmdirSync(path.join(skinPath, x, 'Spine'), { recursive: true, force: true })
//   }
//   // if (!fs.existsSync(basePath, x)) {
//   //   console.log('缺少资源：', x);
//   // }
// })
// const basePath = path.join('D:', 'Spine', 'Wife');
// const dirs = fs.readdirSync(basePath);
// dirs.forEach((id) => {
//   const dir = path.join(basePath, id)

//   // let content = fs.readFileSync(path.join(dir, id + '.atlas.txt')).toString()
//   // content = content.replace(id + '.png', 'Spine.png')
//   // fs.writeFileSync(path.join(dir, id + '.atlas.txt'), content)

//   fs.renameSync(path.join(dir, id + '.atlas.txt'), path.join(dir, 'Spine.atlas.txt'));
//   fs.renameSync(path.join(dir, id + '.png'), path.join(dir, 'Spine.png'));
//   fs.renameSync(path.join(dir, id + '.skel.bytes'), path.join(dir, 'Spine.skel.bytes'));
// })
// console.log(dirs)


// const tmpPath = path.join(resPath, 'LuaAssets', 'image', 'scene', 'battlefield', 'building', '3');

// fs.readdirSync(tmpPath).forEach((fileName) => {
//   if (!fileName.endsWith('jpg')) return;
//   const fullPath = path.join(tmpPath, fileName);
//   child_process.execSync(`magick ${fullPath} -resize 50% ${fullPath}`);
// })

// const tmpPath = path.join(resPath, 'Partial', 'Head');
// fs.readdirSync(tmpPath).forEach((fileName) => {
//   fs.renameSync(path.join(tmpPath, fileName), path.join(tmpPath, fileName.replace('PakUserFigureHead', '')));
// }) 33
// 给全部道具添加高光
// const lightPath = path.join(resPath, 'light.png');
// const basePath = path.join(resPath, 'CDN', 'Partial', 'Props')
// const files = fs.readdirSync(basePath).filter((x) => !x.endsWith('meta'))
// for (let index = 0; index < files.length; index++) {
//   const fullPath = path.join(basePath, files[index]);
//   console.log(`${index + 1} / ${files.length}处理图片：`, fullPath);
//   child_process.execSync(`magick ${fullPath} -gravity center -compose over ${lightPath} -colorspace sRGB -composite ${fullPath}`)
// }
// console.log('处理完毕');

// const wifeIconPath = path.join('D:', 'Spine', 'Icon');
// const iconPath = path.join(cdnPath, 'Partial', 'Skin');
// // const boxPath = path.join('D:', 'Spine', 'box.png');
// const lightPath = path.join('D:', 'Spine', 'light.png');
// fs.readdirSync(iconPath).forEach((dirName) => {
//   // if (fileName.endsWith('meta')) {
//   //   return;
//   // }
//   // 改名
//   // const id = fileName.substring(11, 13);
//   // fs.renameSync(path.join(wifeIconPath, fileName), path.join(wifeIconPath, `Wife${parseInt(id, 10)}.png`))
//   const oldFilePath = path.join(iconPath, dirName, `icon_${dirName}.png`);
//   if (!fs.existsSync(oldFilePath)) {
//     console.log(`${dirName} 中不存在icon`)
//     return;
//   }

//   // child_process.execSync(`magick ${oldFilePath} -resize 115x115! ${oldFilePath}`)
//   child_process.execSync(`magick ${oldFilePath} -gravity center -compose over ${lightPath} -colorspace sRGB -composite ${oldFilePath}`)
  
// })

// const tagPath = path.join(resPath, 'L10n', 'zh_hans', 'Image', 'Aliance', 'Tag', 'AllianceOther2.png')
// console.log(fs.existsSync(tagPath));
// child_process.execSync(`magick 128x64.png -gravity center -compose over ${tagPath} -colorspace sRGB -composite ${tagPath}`)


function GetAllTexturePathes(parentPath, filePathes) {
  const pathes = fs.readdirSync(parentPath);
  pathes.forEach((fileName) => {
    let isFile = fileName.indexOf('.') >= 0;
    const fullPath = path.join(parentPath, fileName)
    if (fileName.indexOf('VERSION') >= 0) return;
    if (fileName.indexOf('sheet') >= 0) return;
    if (!isFile && fileName.toLowerCase().indexOf('placeholder') >= 0) return;
    if (fullPath.indexOf('num' + path.sep) >= 0) return;
    if (isFile) {
      const lowerName = fileName.toLowerCase();
      if (lowerName.endsWith('png') || lowerName.endsWith('jpg') || lowerName.endsWith('jpeg')) { 
        filePathes.push(fullPath);
      }
    } else {
      GetAllTexturePathes(path.join(fullPath), filePathes);
    }
  });
}

function getNearValue(x) {
  let power = 0;
  while(2 ** power <= x) power += 1;
  power -= 1;
  const minV = 2 ** power;
  const maxV = 2 ** (power + 1)
  return (maxV - x > x -minV) ? minV : maxV;
}



// textureType: 0    Default
// textureType: 8    Sprite

// TOSmaller : 3
// TOLarge: 2
// TONearest: 1
// None: 0
function main() {
  // if (true) {
  //   resizeImg('D:/Workspace/sesame-unity/sesame/Assets/Game/Res/Res/Dynamic/User/Scene/scene2_user_bg0.jpg', '512x512', '750x760')
  //   resizeImg('D:/Workspace/sesame-unity/sesame/Assets/Game/Res/Res/Dynamic/User/Scene/scene2_user_bg637.jpg', '512x512', '750x760')
  //   resizeImg('D:/Workspace/sesame-unity/sesame/Assets/Game/Res/Res/Dynamic/User/Scene/scene2_user_box0.png', '512x512', '750x514')

  //   return;
  // }
  // if (true) {
  //   expendBatch("D:/Workspace/sesame-unity/sesame/Assets/Game/Res/Res/Dynamic/Alliance/BossRole/", 724, 680)
  //   expendBatch("D:/Workspace/sesame-unity/sesame/Assets/Game/Res/Res/Dynamic/Alliance/FightRole/", 724, 680)

  //   return
  // }
  const resJson = fs.readFileSync(resPath.replace('Res', 'Config/res.json')).toString();
  const resObj = JSON.parse(resJson);
  const checkKeys = {};
  for (const key in resObj) {
    const lastIdx = resObj[key].path.lastIndexOf('/');
    const lastIdx2 = resObj[key].path.indexOf('{n}');
    const subKey = resObj[key].path.substring(0, Math.min(lastIdx, lastIdx2 == -1 ? lastIdx : lastIdx2));
    checkKeys[subKey] = true;
  }

  const tmpPath = 'Res/';

  const basePath = resPath.replace(/\\/gi, '/') + '/' // + tmpPath;
  console.log('basePath:', basePath);
  var filePathes = [];
  let specialPath = basePath;
  let oldSizeStrTarget = null;

  // specialPath = basePath + tmpPath;
  // oldSizeStrTarget = '750x400';

  GetAllTexturePathes(specialPath, filePathes);
  const logs = [];
  var idx = 0;
  var idx2 = 0;
  const count = filePathes.length;
  for (let index = 0; index < count; index++) {
    const x = filePathes[index];
    const imgInfo = getInfo(x);
    if (imgInfo.width < 400 || imgInfo.height < 400) {
      const formatX = x.replace(/\\/gi, '/');
      // TODO 转成 4的倍数
      if (imgInfo.width % 4 != 0 && imgInfo.height % 4 != 0) {
        if (formatX.indexOf('Res/View/Battle/Battle/Sprite') > -1) {
          continue;
        }
        const newWidth = Math.ceil(imgInfo.width / 4) * 4;
        const newHeight = Math.ceil(imgInfo.height / 4) * 4;
        console.log(`${idx2} - [${imgInfo.width}, ${imgInfo.height}] => [${newWidth}, ${newHeight}] :\t ${formatX}  ${formatX.replace(basePath, '')}    `)
        if (specialPath != basePath) {
           child_process.exec(`magick ${x} -resize ${newWidth}x${newHeight}! ${x}`)
        }
        
        idx2++;
      }
      continue;
    }
    const newWidth = getNearValue(imgInfo.width); 
    const newHeight = getNearValue(imgInfo.height);
    if (newHeight == imgInfo.height && newWidth == imgInfo.width) {
      continue;
    }
    // if (imgInfo.height <= 700 && imgInfo.width <= 700) continue;
    const subPath = x.replace(/\\/gi, '/').replace(basePath, '');
    const newSizeStr = `${newWidth}x${newHeight}`
    const oldSizeStr = oldSizeStrTarget ?? `${imgInfo.width}x${imgInfo.height}`
    const newSubPath = x.replace('.', `_${oldSizeStr}.`)
    if (specialPath != basePath) {
      console.log(`${idx} - [${imgInfo.width}, ${imgInfo.height}] => [${newWidth}, ${newHeight}] :\t ${newSubPath.replace(/\\/gi, '/')}   _${oldSizeStr} `)
      resizeImg(x, newSizeStr, oldSizeStr)
    } else {
      console.log(`${idx} - [${imgInfo.width}, ${imgInfo.height}] => [${newWidth}, ${newHeight}] :\t ${x.replace(/\\/gi, '/')}  ${x.replace(/\\/gi, '/').replace(basePath, '')}   _${oldSizeStr} `)

      for (const key in checkKeys) {
        if (subPath.indexOf(key) > -1) {
          logs.push(key);
          break;
        }
      }
    }
    idx++;

    // if (content.indexOf("textureType: 0") > 0) { // Texture
    //   if (content.indexOf('nPOTScale: 0') > 0) {
    //     // console.log('nPOTScale:', x);
    //     content = content.replace('nPOTScale: 0', "nPOTScale: 1");
    //     fs.writeFileSync(x, content);
    //   }
    // } else if (content.indexOf("textureType: 8") > 0) { // Sprite
    //   var info = getInfo(imageFilePath);
    //   if (info.width > 1334 || info.height > 1334) {
    //     if (info.width % 1024 != 0 || info.width % 1024 != 0) {
    //       console.log('额外处理：', JSON.stringify(info), imageFilePath);
    //     }
    //   } else if (info.width > 1024 || info.height > 1024) {
    //     if (info.width % 1024 != 0 || info.width % 1024 != 0) {
    //       const newMeta = x.replace(`${curType}.meta`, `_${info.width}x${info.height}${curType}.meta`)
    //       const newImg = newMeta.replace('.meta', '');
          
    //       if (imageFilePath.indexOf('Common') > 0) {
    //         child_process.execSync(`magick ${imageFilePath} -resize 512x1024! ${imageFilePath}`);
          
    //         fs.renameSync(imageFilePath, newImg);
    //         fs.renameSync(x, newMeta);
    //         console.log(`${idx++ } / ${count} 直接toNearest`, imageFilePath)
    //       }
    //     }
    //   } else {
    //     if (info.width % 4 != 0 || info.height % 4 != 0) {
    //       // 不是四的倍数, 需要扩展成4的倍数
    //       var width = Math.ceil(info.width / 4) * 4;
    //       var height = Math.ceil(info.height / 4) * 4;
          
    //       if(!new RegExp("[\u4E00-\u9FA5]+").test(imageFilePath)){
    //         console.log('resize ', JSON.stringify(info), ' ==> ', width, height, imageFilePath)
    //         child_process.exec(`magick ${imageFilePath} -resize ${width}x${height}! ${imageFilePath}`);
    //       } else {
    //         console.log('error:', imageFilePath);
    //       }
    //     }
    //   }
    // }
  }
  logs.forEach(element => {
    console.log('**********', element);
  });
  console.log('count:', idx);
}
// main();
// expendBatch("D:/Workspace/sesame-unity/sesame/Assets/Game/Res/CDN/Dynamic/RaiseArmy/shopRole/", 550, 1121)

// const newDir = path.join(resPath, 'Res', 'View', 'AreaList', 'Login', 'Bg2')
// resizeBatch(newDir, 1024, 2048)
// child_process.execSync(`mogrify -path ${newDir}/ -resize 512x1024! ${newDir}/*_512x1024.jpg`)

function GetAllFiles(dirPath, filePathes, fileTypes) {
  const pathes = fs.readdirSync(dirPath);
  pathes.forEach((fileName) => {
    let isFile = fileName.indexOf('.') >= 0;
    const fullPath = path.join(dirPath, fileName)
    if (fileName.indexOf('VERSION') >= 0) return;
    if (fileName.indexOf('sheet') >= 0) return;
    if (!isFile && fileName.toLowerCase().indexOf('placeholder') >= 0) return;
    if (isFile) {
      const lowerName = fileName.toLowerCase();
      if (fileTypes) {
        if (typeof fileTypes === 'string') {
          if (lowerName.endsWith(fileTypes)) {
            filePathes.push(fullPath);
          }
        } else if (Array.isArray(fileTypes)) {
          for (let index = 0; index < fileTypes.length; index++) {
            if (lowerName.endsWith(fileTypes[index])) {
              filePathes.push(fullPath);
              break;
            }
          }
        }
      } else {
        filePathes.push(fullPath);
      }
      if (lowerName.endsWith('png') || lowerName.endsWith('jpg') || lowerName.endsWith('jpeg')) { 
      }
    } else {
      GetAllFiles(path.join(fullPath), filePathes, fileTypes);
    }
  });
}

/** 
 * 检查L10n的资源是否有被用到
 * 1、查找prefab的L10n资源， 如果没用到的先丢到LuaAssets的L10N下，顺便检查文件是否存在
 * 2、检查res.json中是否有用到该资源 
 **/
 


async function checkL10n() {
  // 查找代码里的多语言图片引用
  const allCodeFilePathes = [];
  GetAllFiles(resPath.replace(/\\/gi, '/').replace('Assets/Game/Res', 'TsProject/src/game/'), allCodeFilePathes, 'ts')
  // console.log('代码数量：', allCodeFilePathes.length);
  const allPrefabFilePathes = [];
  GetAllFiles(resPath, allPrefabFilePathes, 'prefab')
  // console.log('prefab数量：', allPrefabFilePathes.length);

  // 查找代码中的多语言图片引用
  const waitCheckPathes = [].concat(allPrefabFilePathes);
  console.log(waitCheckPathes.length)
  const keepImgPathes = {};
  waitCheckPathes.forEach((x) => {
    const content = fs.readFileSync(x);
    var r = /Res\/L10n\/.*?(.png|.jpg|.jpeg)/gi;// /Res\/L10n\/.*?\.jpg/gi
      while((result = r.exec(content))){
        keepImgPathes[result[0]] = 1;
      }
  });
  
  // 查找res.json 的过滤目录
  const resJson = fs.readFileSync(resPath.replace('Res', 'Config/res.json')).toString();
  const resObj = JSON.parse(resJson);
  const checkKeys = [];
  for (const key in resObj) {
    if (resObj[key].path.indexOf('L10n') == -1) {
      continue;
    }
    const lastIdx = resObj[key].path.lastIndexOf('/');
    const lastIdx2 = resObj[key].path.indexOf('{n}');
    const subKey = resObj[key].path.substring(0, Math.min(lastIdx, lastIdx2 == -1 ? lastIdx : lastIdx2));
    checkKeys.push(subKey);
  }

  // 开始处理
  const l10nAllImgs = [];
  GetAllFiles(path.join(resPath, 'Res/L10n/zh_hans/Image'), l10nAllImgs, ['png', 'jpg']);
  // console.log(l10nAllImgs.length);
  const noKeeps = [];
  const formatResPath  = resPath.replace(/\\/gi, '/') + '/';
  for (let index = 0; index < l10nAllImgs.length; index++) {
    const imgpath = l10nAllImgs[index].replace(/\\/gi, '/').replace(formatResPath, '');
    let keep = false;
    for (let j = 0; j < checkKeys.length; j++) {
      if (imgpath.indexOf(checkKeys[j]) > -1) {
        keep = true;
        break;
      }
    }
    if (!keep) {
      keep = keepImgPathes[imgpath] != null;
    }
    if (!keep) {
      noKeeps.push(l10nAllImgs[index]);
    }
  }

  // 将没有用到的资源丢到
  console.log('删除数量:', noKeeps.length);
  for (let index = 0; index < noKeeps.length; index++) {
    const element = noKeeps[index];
    const targetPath = element.replace('L10n', 'LuaAssets/L10n')
    const newFileDirPath = targetPath.substring(0, targetPath.lastIndexOf(path.sep))
    if (!fs.existsSync(newFileDirPath)) {
      fs.mkdirSync(newFileDirPath, { recursive : true });
    }
    fs.renameSync(element, targetPath)
  }
}

// checkL10n();
